package com.demo.oauth2jFinalShiroServer.web;

import java.util.ArrayList;
import java.util.List;

import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import com.demo.oauth2jFinalShiroServer.cache.NoteCache;
import com.demo.oauth2jFinalShiroServer.common.CommonResult;
import com.demo.oauth2jFinalShiroServer.model.Note;
import com.jfinal.core.Controller;

public class ResourceController extends Controller {

	// url=/res/site
	public void site(){
		CommonResult<String> result = new CommonResult<>();
		result.setData("www.netease.com");
		renderJson(result);
	}
	
	// url=/res/addNote?title=[title]&content=[content]&token=[token]
	public void addNote(){
		CommonResult<Note> result = new CommonResult<>();
		try {
			getRequest().setCharacterEncoding("UTF-8");
			String title = getPara("title");
			String content = getPara("content");
			Subject subject = SecurityUtils.getSubject();
			String username = (String)subject.getPrincipal();
			Note note = Note.addNote(title, content);
			NoteCache.USER_NOTE_MAP.put(username, note);
			result.setData(note);
		} catch (Exception e) {
			result.setMsg(e.getMessage());
		}
		renderJson(result);
	}
	
	// url=/res/note?token=[token]
	public void note(){
		CommonResult<List<Note>> result = new CommonResult<>();
		try {
			Subject subject = SecurityUtils.getSubject();
			String username = (String)subject.getPrincipal();
			List<Note> notes = new ArrayList<>(); 
			notes.addAll(NoteCache.USER_NOTE_MAP.get(username));
			result.setData(notes);
		} catch (Exception e) {
			result.setMsg(e.getMessage());
		}
		renderJson(result);
	}
	
	// url=/res/userInfo?token=[token]
	public void userInfo() throws OAuthSystemException {
		CommonResult<String> result = new CommonResult<>();
		try {
			Subject subject = SecurityUtils.getSubject();
			String username = (String)subject.getPrincipal();
			result.setData(username);
		} catch (Exception e) {
			result.setMsg(e.getMessage());
		}
		renderJson(result);
	}

	
}
